package com.thb.pay.core.json;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.thb.pay.core.annotation.SensitiveInfo;
import com.thb.pay.core.enums.SensitiveTypeEnum;
import com.thb.pay.core.utils.SensitiveInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;


/**
 * @author lucky
 * @ClassName SensitiveInfoSerialize
 * @Description 在fastjson中使用此过滤器进行脱敏操作
 * <p>在对应的VO 加对应的序列属性 加上注解 @SensitiveInfo ,返回string : JSON.toJSONString(object, new ValueSensitiveInfoFilter())</p>
 * @date 2019/11/11
 * @Version 1.0
 */
@Slf4j
@Component
public class ValueSensitiveInfoFilter implements ValueFilter {


    @Override
    public Object process(Object object, String name, Object value) {
        if (null == value || !(value instanceof String) || ((String) value).length() == 0) {
            return value;
        }
        try {
            Field field = object.getClass().getDeclaredField(name);
            SensitiveInfo sensitiveInfo;
            if (String.class != field.getType() || (sensitiveInfo = field.getAnnotation(SensitiveInfo.class)) == null) {
                return value;
            }
            String resultValue = null;
            SensitiveTypeEnum sensitiveTypeEnum = sensitiveInfo.value();
            switch (sensitiveTypeEnum) {
                case CHINESE_NAME: {
                    resultValue = SensitiveInfoUtils.chineseName(String.valueOf(value));
                    break;
                }
                case ID_CARD: {
                    resultValue = SensitiveInfoUtils.idCardNum(String.valueOf(value));
                    break;
                }
                case FIXED_PHONE: {
                    resultValue = SensitiveInfoUtils.fixedPhone(String.valueOf(value));
                    break;
                }
                case MOBILE_PHONE: {
                    resultValue = SensitiveInfoUtils.mobilePhone(String.valueOf(value));
                    break;
                }
                case ADDRESS: {
                    resultValue = SensitiveInfoUtils.address(String.valueOf(value), 4);
                    break;
                }
                case EMAIL: {
                    resultValue = SensitiveInfoUtils.email(String.valueOf(value));
                    break;
                }
                case BANK_CARD: {
                    resultValue = SensitiveInfoUtils.bankCard(String.valueOf(value));
                    break;
                }
                case CNAPS_CODE: {
                    resultValue = SensitiveInfoUtils.cnapsCode(String.valueOf(value));
                    break;
                }
            }
            if (resultValue != null) {
                return resultValue;
            }
        } catch (NoSuchFieldException e) {
            log.warn("ValueDesensitizeFilter the class {} has no field {}", object.getClass(), name);
        }
        return value;
    }
}

